<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <div class="flex items-center">
        <div class="border-arrow" @click="toPrevPage">
          <FontIcon icon="icon-left" />
        </div>
        <div class="text-[#242930] ml-4">
          {{ t("expiry_detail.edit_expiry") }} - {{ verQuery.name }}
        </div>
      </div>
    </vxe-card>

    <vxe-card title="" class="w-full mt-4" :border="false" :padding="false">
      <div class="wrap p-[20px]">
        <div :class="TITLE_CLASS">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("expiry_detail.material_info") }}
            </div>
          </div>
        </div>
        <div class="relative">
          <el-descriptions :column="2" border class="desc-item">
            <el-descriptions-item
              v-for="item in keyDescription"
              :key="item.key"
              label-align="right"
            >
              <template #label>
                <div class="cell-item">{{ t(item.name) }}：</div>
              </template>
              {{ materialData[item.key] }}
            </el-descriptions-item>
          </el-descriptions>

          <component
            :is="
              useRenderIcon(
                materialData['publish_status'] == 1 ? PublishSvg : PullSvg
              )
            "
            class="w-[120px] h-[92px] absolute right-0 bottom-0"
          />
        </div>

        <div :class="[TITLE_CLASS, 'mt-4']">
          <div class="flex items-center">
            <div class="w-[2px] h-[14px] bg-[--el-color-primary]" />
            <div class="text-[#242930] text-sm ml-[10px]">
              {{ t("expiry_detail.expiry_info") }}
            </div>
          </div>
        </div>

        <el-tabs
          v-model="expiryType"
          v-loading="loading"
          type="border-card"
          addable
          class="expiry-tab"
          @edit="handleTabsEdit"
        >
          <template #add-icon>
            <iconify-icon-online icon="ion:add" />
            {{ t("expiry_detail.add_status") }}
          </template>
          <el-tab-pane
            v-for="(item, i) in expiryTypeList"
            :key="item.name"
            :label="item.title"
            :name="item.name"
            :closable="i !== 0"
          >
            <template #label>
              <span>
                {{ item.title }}
              </span>
              <el-link
                type="primary"
                :underline="false"
                @click="tabNameClick(item)"
              >
                <component
                  :is="useRenderIcon(Edit)"
                  class="text-[16px] ml-1 mt-[1px]"
                />
              </el-link>
            </template>

            <el-form
              ref="expiryRef"
              :model="item.expiryData"
              :rules="expiryRules"
              label-suffix=" :"
              label-width="130px"
              class="text-[--autata-font-gray-color]"
            >
              <!--              <el-form-item label="设置生效时间段" prop="isActivate">-->
              <!--                <el-switch v-model="item.expiryData.isActivate" />-->
              <!--              </el-form-item>-->

              <el-form-item
                v-if="i !== 0"
                :label="t('expiry_detail.active_time')"
                prop="activeTime"
                class="time-form-item"
              >
                <el-time-picker
                  v-model="item.expiryData.activeTime"
                  class="!w-[308px]"
                  is-range
                  range-separator="-"
                  :start-placeholder="t('expiry_detail.start_time')"
                  :end-placeholder="t('expiry_detail.end_time')"
                  value-format="HH:mm:ss"
                />
                <!--                <el-select v-model="item.expiryData.isFront" class="!w-[200px]">-->
                <!--                  <el-option :value="1" label="前">前</el-option>-->
                <!--                  <el-option :value="0" label="后">后</el-option>-->
                <!--                </el-select>-->
              </el-form-item>

              <el-form-item
                :label="t('expiry_detail.expiry_time')"
                prop="expiryType"
                class="!flex-wrap"
              >
                <el-select
                  v-model="item.expiryData.expiryType"
                  class="!w-[200px]"
                >
                  <el-option
                    v-for="type in expiryTypes"
                    :key="type.value"
                    :value="type.value"
                    :label="type.label"
                  />
                </el-select>
                <div
                  v-if="item.expiryData.expiryType == '5'"
                  class="flex items-center"
                >
                  <vxe-input
                    v-model="item.expiryData.expiryDay"
                    class="ml-2 !w-[100px]"
                    placeholder="≥0"
                    type="number"
                    min="0"
                  />
                  <span class="ml-2 inline-block">{{
                    t("expiry_detail.expiry_day")
                  }}</span>
                </div>
                <div
                  v-if="item.expiryData.expiryType == '1'"
                  class="flex items-center"
                >
                  <vxe-input
                    v-model="item.expiryData.expiryHour"
                    class="ml-2 !w-[100px]"
                    placeholder="≥0"
                    type="number"
                    min="0"
                  />
                  <span class="mx-2 inline-block">{{
                    t("expiry_detail.hours")
                  }}</span>
                  <vxe-input
                    v-model="item.expiryData.expiryMin"
                    class="ml-2 !w-[100px]"
                    placeholder="≥0"
                    type="number"
                    min="0"
                  />
                  <span class="ml-2 inline-block">{{
                    t("expiry_detail.minutes")
                  }}</span>
                </div>

                <span
                  class="text-primary cursor-pointer ml-[20px]"
                  @click="item.expand = !item.expand"
                  >{{
                    item.expand
                      ? t("expiry_detail.collapse")
                      : t("expiry_detail.expand")
                  }}</span
                >
              </el-form-item>

              <el-collapse-transition>
                <div v-if="item.expand" class="bg-[#F5F9FF] py-[20px]">
                  <el-form-item
                    v-for="config in configList"
                    :key="config.key"
                    :label="`${config.name}${t('expiry_detail.expiry_time')}`"
                    prop="flavorTime"
                  >
                    <vxe-input
                      v-model="item.expiryData.configs[config.key].hour"
                      class="!w-[100px]"
                      placeholder="≥0"
                      type="number"
                      min="0"
                    />
                    <span class="mx-2 inline-block">{{
                      t("expiry_detail.hours")
                    }}</span>
                    <vxe-input
                      v-model="item.expiryData.configs[config.key].min"
                      class="!w-[100px]"
                      placeholder="≥0"
                      type="number"
                      min="0"
                    />
                    <span class="ml-2 inline-block">{{
                      t("expiry_detail.minutes")
                    }}</span>
                  </el-form-item>
                </div>
              </el-collapse-transition>

              <el-form-item
                :label="t('expiry_detail.storage_method')"
                class="mt-[16px]"
                prop="storageMethod"
              >
                <el-select
                  v-model="item.expiryData.storageMethod"
                  class="!w-[100px]"
                >
                  <el-option
                    v-for="type in storageMethods"
                    :key="type.value"
                    :value="type.value"
                    :label="type.label"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div
        class="flex items-center justify-end mt-[16px] px-[20px] py-[10px] border-t border-[--autata-border-color]"
      >
        <el-button @click="cancel">{{ t("expiry_detail.back") }}</el-button>
        <el-button type="primary" @click="confirm">{{
          t("expiry_detail.save")
        }}</el-button>
      </div>
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, ref, h, reactive } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import { isArray, isNullOrUnDef, useGlobal } from "@pureadmin/utils";
import { useI18n } from "vue-i18n";
import {
  CategoryProp,
  expiryAdd,
  expiryGetList,
  expiryUpd,
  getCategory,
  getMaterialDetList,
  MaterialDetailProp,
  MaterialOtherProp
} from "@/api/expiry/expiry";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  ElMessage,
  ElMessageBox,
  ElTooltip,
  FormRules,
  TabPaneName
} from "element-plus";
import ClockOn from "@/assets/svg/clock_on.svg?component";
import ClockOff from "@/assets/svg/clock_off.svg?component";
import Edit from "@/assets/svg/edit.svg?component";
import PublishSvg from "@/assets/svg/shangjia.svg?component";
import PullSvg from "@/assets/svg/xiajia.svg?component";
import { cloneDeep, omit, pick } from "lodash-unified";
import { convertToSeconds } from "@/utils/tool";
import { getPersonList } from "@/api/expiry/person";
import {
  CONFIG_LIST,
  EXPORT_LIST,
  STORAGE_LIST,
  WEEK_LIST
} from "@/views/expiry/material/materialManage/constants";
import { userKey } from "@/utils/auth";

const { t } = useI18n();

defineOptions({
  name: "expiryDetail"
});

interface ExpiryDataProp {
  isActivate: boolean;
  activeTime: string[];
  isFront: 1 | 0;
  expiryType: string;
  expiryDay?: string;
  cycle?: string[];
  cycleType?: number;
  isDefault?: number;
  expiryHour: string;
  expiryMin: string;
  expiryAlert: boolean;
  storageMethod: string;
  personId: string;
  configs: {
    [key: string]: {
      hour: string;
      min: string;
      key: string;
      name: string;
    };
  };
}

type expiryListType = {
  name: string;
  title: string;
  expand: boolean;
  expiryData: ExpiryDataProp;
};

// region 声明ref变量集合
const TITLE_CLASS = "flex items-center justify-between pb-[12px]";
const expiryTypes = EXPORT_LIST;
const storageMethods = STORAGE_LIST;
const persons = ref([]);
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

let tabIndex = 1;
const expiryType = ref("");
const expiryTypeList = ref<expiryListType[]>([]);
const categoryList = ref([]);
const materialData = ref<Partial<MaterialDetailProp & MaterialOtherProp>>({});
const loading = ref(false);
const configList = ref(CONFIG_LIST);

const expiryRules = reactive<
  FormRules<{
    activeTime: string;
    storageMethod: string;
    expiryType: string;
  }>
>({
  activeTime: [
    {
      required: true,
      message: t("expiry_detail.active_time_required"),
      trigger: "change"
    }
  ],
  storageMethod: [
    {
      required: true,
      message: t("expiry_detail.storage_method_required"),
      trigger: "change"
    }
  ],
  expiryType: [
    {
      required: true,
      message: t("expiry_detail.expiry_time_type_required"),
      trigger: "change"
    }
  ]
});

let resData = [];
let verQuery = ref({
  versionId: "",
  name: ""
});

const keyDescription = [
  { key: "type", name: "expiry_detail.type" },
  { key: "name", name: "expiry_detail.material_name" },
  { key: "material_id", name: "expiry_detail.material_code" },
  { key: "type_name", name: "expiry_detail.category" },
  { key: "fpMaterial", name: "expiry_detail.finished_product" },
  { key: "materialPrice", name: "expiry_detail.unit_price" },
  { key: "conversion", name: "expiry_detail.conversion" },
  { key: "note", name: "expiry_detail.remark" }
];

const expiryRef = ref();
const ONE_DAY_SECOND = 86400;

// endregion

// region 公共方法的集合
function ClockRender(props: { item: any; handleKey: string }) {
  return h(
    ElTooltip,
    {
      content: "设为提醒时间",
      placement: "top-start"
    },
    () => {
      return h(
        useRenderIcon(props.item[props.handleKey] ? ClockOn : ClockOff),
        {
          class: "clock",
          onClick: () => {
            setAlert(props.item, props.handleKey);
          }
        }
      );
    }
  );
}

function init() {
  getCategory().then(res => {
    categoryList.value = res.data;
  });

  const query = route.query?.verQuery;
  verQuery.value = JSON.parse(query as string);
  // getPersonList({ size: 0, start_page: 0 }).then(res => {
  //   persons.value = res.data.map(v => {
  //     return {
  //       value: v.id,
  //       label: v.name
  //     };
  //   });
  // });

  if (route.query?.row) {
    const find = JSON.parse(route.query?.row as string);
    // getMaterialDetList({ size: 0 }).then(res => {
    //   const find = res.data.find(v => v.id == Number(route.query?.id));
    materialData.value = {
      ...find,
      type: t("expiry_detail.type_value"),
      fpMaterial: t("expiry_detail.finished_product_value"),
      materialPrice: t("expiry_detail.unit_price_value"),
      conversion: t("expiry_detail.conversion_value")
    };
    // });
    if (find.material_id) {
      getExpiryList(find.material_id);
    }
  }
}

function addExpiry(value: string) {
  const newTabName = `${++tabIndex}`;
  const configs = {};
  configList.value.forEach(v => (configs[v.key] = { hour: "", min: "", ...v }));
  expiryTypeList.value.push({
    title: value,
    name: newTabName,
    expand: true,
    expiryData: {
      isActivate: false,
      activeTime: tabIndex === 1 ? ["00:00:00", "23:59:59"] : [],
      isFront: 1,
      expiryType: "",
      expiryHour: "",
      expiryMin: "",
      expiryAlert: false,
      storageMethod: "",
      personId: "",
      configs
    }
  });
  expiryType.value = newTabName;
}

function secondsToHms(seconds: number) {
  // 计算小时数
  const hours = Math.floor(seconds / 3600);
  // 计算剩余的秒数
  seconds %= 3600;
  // 计算分钟数
  const minutes = Math.floor(seconds / 60);
  // 计算剩余的秒数
  seconds %= 60;

  // 格式化输出
  return [hours, minutes, seconds];
}

async function getExpiryList(materialId: string) {
  if (verQuery.value.versionId) {
    const { versionId } = verQuery.value;
    const param = {
      materialId,
      versionId
    };
    loading.value = true;
    try {
      const res = await expiryGetList(param);
      if (res.data.length) {
        resData = res.data;
        expiryTypeList.value = res.data.map((v, i) => {
          const config = JSON.parse(v.config || "[]");
          const [expiryHour, expiryMin] =
            v.expiryType == "1" ? secondsToHms(v.expiryTime) : ["", ""];
          let expiryDay = 0;
          if (v.expiryType == "5") {
            expiryDay = Number(v.expiryTime) / ONE_DAY_SECOND;
          }
          const configs = {};

          configList.value.forEach(h => {
            // const find = config.find(k => k.key === v.key);
            configs[h.key] = {
              hour: "",
              min: "",
              ...h
            };
          });
          if (isArray(config)) {
            for (const key in configs) {
              const find = config.find(k => k.key === key);
              if (find) {
                configs[key].hour = find.hour || "";
                configs[key].min = find.min || "";
              }
            }
          }
          return {
            title: v.title,
            name: String(i + 1),
            expand: true,
            expiryData: {
              // ...v,
              id: v.id,
              versionId,
              activeTime: i === 0 ? [] : [v.startActiveTime, v.endActiveTime],
              expiryType: String(v.expiryType),
              // isDefault: isNullOrUnDef(v.isDefault)
              //   ? i === 0
              //     ? 1
              //     : 0
              //   : v.isDefault,
              isDefault: i === 0 ? 1 : 0,
              expiryDay,
              expiryHour,
              expiryMin,
              expiryAlert: v.expiryAlert,
              thawAlert: config.thawAlert,
              storageMethod: v.storageMethod,
              personId: v.personId,
              configs
            }
          };
        }) as any[];
        expiryType.value = expiryTypeList.value[0].name;
      }
      loading.value = false;
    } catch (e) {
      loading.value = false;
    }
  }
}

// endregion

// region 组件事件的集合
const toPrevPage = () => {
  router.push({
    name: "expiryMaterialDetail",
    query: {
      ...verQuery.value
    }
  });
};

const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: "remove" | "add"
) => {
  if (action === "add") {
    proxy.$auMessageBox
      .prompt(t("expiry_detail.expiry_title"), t("notice.title"), {
        inputPlaceholder: t("expiry_detail.expiry_title_placeholder"),
        inputValidator: (value: string) => {
          return !(!value || value?.trim() === "");
        },
        inputErrorMessage: t("expiry_detail.expiry_title_empty")
      })
      .then(({ value }) => {
        addExpiry(value);
      });
  } else if (action === "remove") {
    const tabs = expiryTypeList.value;
    let activeName = expiryType.value;
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        }
      });
    }

    expiryType.value = activeName;
    expiryTypeList.value = tabs.filter(tab => tab.name !== targetName);
  }
};

const setAlert = (item: ExpiryDataProp, key: string) => {
  item[key] = !item[key];
};

const tabNameClick = (item: expiryListType) => {
  proxy.$auMessageBox
    .prompt(t("expiry_detail.expiry_title"), t("notice.title"), {
      inputPlaceholder: t("expiry_detail.expiry_title_placeholder"),
      inputValue: item.title,
      inputValidator: (value: string) => {
        return !(!value || value?.trim() === "");
      },
      inputErrorMessage: t("expiry_detail.expiry_title_empty")
    })
    .then(({ value }) => {
      item.title = value;
    });
};

function getUserInfo() {
  let accountId, businessId;
  const userInfo = localStorage.getItem(userKey);
  if (userInfo) {
    accountId = JSON.parse(userInfo).accountId;
    businessId = JSON.parse(userInfo).businessId;
  }
  return {
    accountId,
    businessId
  };
}

function handleExpireData(list: expiryListType[]) {
  const expiryList = [];
  const keyList = [
    "expiryHour",
    "expiryMin",
    "configs",
    "expiryDay",
    "activeTime"
  ];

  if (isArray(list)) {
    for (const item of list) {
      const expiryData = item.expiryData;
      const pickData = pick(expiryData, keyList);
      let expiryTime = convertToSeconds(
        0,
        pickData.expiryHour,
        pickData.expiryMin
      );
      if (expiryData.expiryType == "3" || expiryData.expiryType == "2") {
        expiryTime = 0;
      } else if (expiryData.expiryType == "4") {
        expiryTime = ONE_DAY_SECOND;
      } else if (expiryData.expiryType == "5") {
        expiryTime = Number(expiryData.expiryDay) * ONE_DAY_SECOND;
      }
      const configList = [];
      for (const key in expiryData.configs) {
        const conf = expiryData.configs[key];
        if (conf.min || conf.hour) {
          const time = convertToSeconds(0, conf?.hour || 0, conf?.min || 0);
          // if (time <= 0) {
          //   ElMessage.warning(`${conf.name}时间的小时和分钟不能小于等于0`);
          //   return;
          // }
          configList.push({
            key,
            time,
            ...conf
          });
        }
      }
      const omitData = omit(expiryData, keyList);
      const config = JSON.stringify(configList);
      const [startActiveTime, endActiveTime] = expiryData.activeTime ?? [];

      expiryList.push({
        ...omitData,
        expiryTime,
        startActiveTime,
        endActiveTime,
        title: item.title,
        config,
        ...getUserInfo(),
        versionId: verQuery.value.versionId,
        materialId: materialData.value.material_id,
        materialSource: materialData.value.materialSource
      });
    }
  }

  return {
    expiryList: expiryList,
    materialId: materialData.value.material_id,
    versionId: verQuery.value.versionId,
    materialSource: materialData.value.materialSource
  };
}

function checkOverlappingIntervals(intervals) {
  // 按照开始时间排序
  intervals.sort((a, b) => a[0].localeCompare(b[0]));

  // 检查重叠
  const overlappingIndices = [];
  for (let i = 1; i < intervals.length; i++) {
    if (intervals[i][0] < intervals[i - 1][1]) {
      overlappingIndices.push(i - 1, i);
    }
  }

  // 返回重叠的下标
  return overlappingIndices;
}

const confirm = async () => {
  const data = cloneDeep(expiryTypeList.value);
  if (expiryRef.value?.length) {
    for (let i = 0; i < expiryRef.value?.length; i++) {
      const ele = expiryRef.value[i];
      const valid = await ele.validate(valid => valid);
      if (!valid) {
        expiryType.value = data[i]?.name;
        return;
      }
    }
  }

  for (const item of data) {
    if (
      item.expiryData.expiryType == "1" &&
      Number(item.expiryData.expiryMin) <= 0 &&
      Number(item.expiryData.expiryHour) <= 0
    ) {
      proxy.$auMessageBox.alert(
        `${item.title}-${t("expiry_detail.expiry_time")}-${t("expiry_detail.expiry_time_required")}`,
        t("notice.title")
      );
      expiryType.value = item?.name;
      return;
    } else if (
      item.expiryData.expiryType == "5" &&
      !item.expiryData.expiryDay
    ) {
      proxy.$auMessageBox.alert(
        `${item.title}${t("expiry_detail.enter_expiry_day")}`,
        t("notice.title")
      );
      expiryType.value = item?.name;
      return;
    }
  }

  const overlap = checkOverlappingIntervals(
    data.map(item => item.expiryData.activeTime)
  );
  if (overlap.length) {
    let str = "";
    for (let i = 0; i < overlap.length; i++) {
      const index = overlap[i];
      str += `${data[index].title}`;
      if (i !== overlap.length - 1) {
        str += "、";
      }
    }
    proxy.$auMessageBox.alert(
      t("expiry_detail.time_overlap", { titles: str }),
      t("notice.title")
    );
    return;
  }

  const param = handleExpireData(data);
  if (!param) return;
  if (resData.length) {
    expiryUpd(param).then(res => {
      if (res.code === 200) {
        proxy.$message.success(t("expiry_detail.modify_success"));
        toPrevPage();
      }
    });
  } else {
    expiryAdd(param).then(res => {
      if (res.code === 200) {
        proxy.$message.success(t("expiry_detail.add_success"));
        toPrevPage();
      }
    });
  }
};
const cancel = () => {
  proxy.$auMessageBox
    .confirm(t("expiry_detail.confirm_cancel"), t("notice.title"))
    .then(() => {
      toPrevPage();
    });
};
// endregion

onMounted(() => {
  init();
  addExpiry("名称");
});
</script>

<style lang="scss" scoped>
.expiry-tab {
  :deep(.el-tabs__new-tab) {
    width: auto;
    margin-right: 10px;
    color: var(--el-color-primary);
    border: none;
  }
}

.desc-item {
  :deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
    width: 165px;
  }
}

:deep(.clock) {
  width: 24px;
  height: 24px;
  margin-left: 20px;
  cursor: pointer;
  outline: none;
  fill: #9fa6b0;

  &:hover {
    fill: #ea2626;
  }
}

.time-form-item {
  :deep(.el-form-item__content) {
    display: block;
  }
}
</style>
